package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pda.mapper.OrderDosingMapper;
import com.indusfo.spc.pda.pojo.OrderDosing;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.BarCodeRules;
import com.indusfo.spc.service.BatchService;
import com.indusfo.spc.service.RuleService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Service
public class BatchServiceImpl implements BatchService {

    private static final Logger logger = LoggerFactory.getLogger(BatchServiceImpl.class);

    @Resource
    private BatchMapper batchMapper;

    @Autowired
    private BarCodeRules barCodeRules;

    @Resource
    private BatchFlowMapper batchFlowMapper;

    @Resource
    private BatchStationMapper batchStationMapper;

    @Resource
    private ProStationMapper proStationMapper;

    @Resource
    private BatchRepairMapper batchRepairMapper;

    @Resource
    private OrderDosingMapper orderDosingMapper;

    @Resource
    UploadMapper uploadMapper;

    @Resource
    private RuleService ruleService;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public JSONObject insertBatch(Batch batch, Integer num, Integer planNum) {
        try{
            List<String> list = new ArrayList<>();
            if (batch.getOrderId() == null) {
                throw new ModifyFailedException("请选择任务单号");
            }
            if (num == null || num == 0) {
                throw new ModifyFailedException("请填写数量");
            }
            if (batch.getUserId() == null ) {
                throw new ModifyFailedException("请填写用户Id");
            }
            Integer batchNum = batchMapper.querybatchNum(batch.getOrderId());
            if(num + batchNum > planNum){
                throw new ModifyFailedException("投入数量过多,最多再创建:"+(planNum-batchNum));
            }
            Integer ruleId = batchMapper.queryRuleId(batch.getOrderId());
            list=ruleService.batchRule(batch.getOrderId(),num);
//            list = barCodeRules.calculate(ruleId, num);
            // 查询工艺版本
            //查询当前工序
            Integer orderTechId = batchMapper.selectOrderTechIdByOrderId(batch.getOrderId());
            batch.setOrderTechId(orderTechId);
            Integer orderFlowId = batchMapper.queryNowFlowId(orderTechId);
            batch.setOrderFlowId(orderFlowId);
            batch.setOrderFlowStateId(1);




            int row = batchMapper.insertSelective(batch, list);
            if (row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            List<Batch> batchList = new ArrayList<>();
            int i = 1;
            for(String batchCode :list){
                Batch batch1 = new Batch();
                batch1 .setBatchCode(batchCode);
                batch1 .setBatchId(i++);
                batchList.add(batch1);
            }
            updateOrderDosing(batch.getOrderId());
            return JSONObject.oK("新增成功",batchList,list.size());
        } catch ( GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject selectBatch(Batch batch) {
        List<Batch> batchList = null;
        try {
            Integer pagesize = batch.getPagesize();
            Integer pageindex = batch.getPageindex();
            if (pagesize != null && pageindex != null) {
                batch.setIncept(pagesize * (pageindex - 1));
            }
            if (batch.getOrderId() == null) {
                throw new ParamsErrorException("请选择任务单号");
            }
            //查询全部
            batchList = batchMapper.selectBatch(batch);
            if (batchList.isEmpty()) {
                return JSONObject.oK("没有查询到数据", batchList, 0);
            }
            //查询分页总记录数
            int count = batchMapper.countBatch(batch); //返回查询到的总记录数
            return JSONObject.oK("查询成功", batchList, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject delBatch(Long[] batchIds , Long[] productStateIds) {
        try{
            if (batchIds == null || batchIds.length == 0) {
                throw new ParamsErrorException("请选择批号");
            }
            String msg = "";
            for(int i = 0 ; i < productStateIds.length ; i++){
                if(productStateIds[i] != 1){
                    throw new ParamsErrorException("除待投产以外都不能删除");
                }
            }
            int row = batchMapper.delBatch(batchIds);
            if (row == 0) {
                msg = "删除失败";
            } else {
                msg = "删除成功";
                batchMapper.delBatchScrap(batchIds);
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject printBatch(Long[] batchIds) {
        try{
            if (batchIds == null || batchIds.length == 0) {
                throw new ParamsErrorException("请选择批号");
            }
            String msg = "";
            int row = batchMapper.printBatch(batchIds);
            if (row == 0) {
                msg = "打印失败";
            } else {
                msg = "打印成功";
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject printBatchCode(String[] batchCodes) {
        try{
            if (batchCodes == null || batchCodes.length == 0) {
                throw new ParamsErrorException("请选择批号");
            }
            String msg = "";
            int row = batchMapper.printBatchCode(batchCodes);
            if (row == 0) {
                msg = "打印失败";
            } else {
                msg = "打印成功";
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject numBatch(Batch batch) {
        try{
            if (batch.getOrderId() == null || batch.getOrderId() == 0) {
                throw new ParamsErrorException("请选择生产任务单号");
            }
            Batch batchs = batchMapper.selectBatchNum(batch);
            return JSONObject.oK(batchs);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject queryOrder(Order order) {
        try{
            if (order.getOrderNo() == null || order.getOrderNo() == "") {
                throw new ParamsErrorException("请输入生产任务单号");
            }
            Order orders = batchMapper.queryOrder(order);
            if(orders==null){
                throw new ParamsErrorException("未查到生产任务单号");
            }
            if(orders.getExecuteStateId()==null){
                throw new ParamsErrorException("任务单状态不能为空");
            }
            if(orders.getExecuteStateId()==1){
                throw new ParamsErrorException("该任务单未发布，请先发布");
            }
            Order order1=new Order();
            order1.setOrderId(orders.getOrderId());
            order1.setOrderTechId(orders.getOrderTechId());
            orderMapper.updateByPrimaryKeySelective(order1);

            return new JSONObject(200, "查询成功", orders);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject queryBatchOrder(Batch batch) {
        try{
            if (batch.getBatchCode() == null || batch.getBatchCode() == "") {
                throw new ParamsErrorException("请输入批次号");
            }
            Batch batchOrder = batchMapper.queryBatchOrder(batch);
            if(batchOrder == null){
                return new JSONObject(200,"没有查询到数据", batchOrder);
            }
            return new JSONObject(200,"查询成功", batchOrder);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject updateOrderDosing(Integer orderId) {
        try {
            //查询任务单下所有 叫料信息
            List<OrderDosing> orderDosingList=batchMapper.queryOrderDosing(orderId);

            //通过任务单查询下面的所有批次
			List<OrderDosing> orderDosingForBatch=batchMapper.queryOrderDosingForBatch(orderId);

            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (orderDosingList != null) {
                for (OrderDosing dosing : orderDosingList
                ) {
                    oldIds.add(dosing.getMatId());
                }
            }
            if (orderDosingForBatch != null) {
                for (OrderDosing dosing : orderDosingForBatch
                ) {
                    newIds.add(dosing.getMatId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            //删除数据
            if(deleteList.size()!=0){
                batchMapper.deleteOrderDosing(deleteList,orderId);
            }
            //新增或修改
            for (OrderDosing dosing:orderDosingForBatch
                 ) {
                for (OrderDosing dosing1:orderDosingList ) {
                    if(dosing.getMatId().equals(dosing1.getMatId())){
                        dosing.setOrderDosingId(dosing1.getOrderDosingId());
                    }
                }
                dosing.setDosingState(1);
                if(dosing.getOrderDosingId()==null){
                    batchMapper.insertOrderDosing(dosing);
                }else{
                    batchMapper.updateOrderDosing(dosing);
                }

            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, 0);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public String checkExcelContent(Batch batch) {
        String batchCode = batch.getBatchCode();
        if(StringUtils.isEmpty(batchCode)){
            return "批次编码为空";
        }
        if(batchCode.getBytes().length>50){
            return "批次编码长度不能超过50";
        }
        int distinctBatchCode = uploadMapper.queryDistinctBatchCode(batch);
        if(distinctBatchCode>0){
            return "批次编码已存在";
        }

        return null;
    }

    @Override
    public JSONObject updateListBatch(List<Batch> batchList) {
        uploadMapper.updateListBatch(batchList);
        return null;
    }

    @Override
    public String checkParam(Batch batch) {
        Integer orderId = batch.getOrderId();
        Integer userId = batch.getUserId();
        Integer orderTechId = batchMapper.selectOrderTechIdByOrderId(batch.getOrderId());
        batch.setOrderTechId(orderTechId);
        Integer orderFlowId = batchMapper.queryNowFlowId(orderTechId);
        batch.setOrderFlowId(orderFlowId);
        batch.setOrderFlowStateId(1);
        if(orderId==null || "".equals(orderId)){
            return "任务单id为空";
        }
        if(userId==null || "".equals(userId)){
            return "用户id为空";
        }
        return null;
    }

    @Override
    public Integer queryNowFlowId(Integer orderTechId) {
        return  batchMapper.queryNowFlowId(orderTechId);
    }

    /**
     * 保存工序流程
     */
    @Override
    public JSONObject saveBatchFlow(Batch batch) {
        try {
            //判空
            if (batch == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (batch.getBatchId() == null) {
                throw new ParamsErrorException(HintMessage.ORDERID_NULL);
            }

            //获取版本
            Integer batchId = batch.getBatchId();
            //获取list集合
            List<BatchFlow> batchFlowList = new ArrayList<>();
            batchFlowList = batch.getBatchFlowList();
            for (BatchFlow batchFlow : batchFlowList) {
                batchFlow.setBatchId(batchId);
            }


            //获取数据库数据
            BatchFlow batchFlow1 = new BatchFlow();
            batchFlow1.setBatchId(batchId);

            List<BatchFlow> oldbatchFlowList = batchFlowMapper.queryBatchFlow(batchFlow1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldbatchFlowList != null) {
                for (BatchFlow batchFlow : oldbatchFlowList
                ) {
                    oldIds.add(batchFlow.getBatchFlowId());
                }
            }
            if (batchFlowList != null) {
                for (BatchFlow batchFlow : batchFlowList
                ) {
                    newIds.add(batchFlow.getBatchFlowId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = batchFlowMapper.deleteBatchFlow(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (batchFlowList != null) {
                for (BatchFlow batchFlow : batchFlowList
                ) {
                    if (batchFlow.getDataState() == null) {
                        batchFlow.setDataState(1);
                    }
                    if (batchFlow.getSequence() == null) {
                        batchFlow.setSequence(0);
                    }
                    if (batchFlow.getUserId().equals(0)) {
                        batchFlow.setUserId(null);
                    }
                    if (batchFlow.getClasseId().equals(0)) {
                        batchFlow.setClasseId(null);
                    }
                    if (batchFlow.getStationId().equals(0)) {
                        batchFlow.setStationId(null);
                    }
                    if (batchFlow.getStartDate().equals(0)) {
                        batchFlow.setDataState(null);
                    }
                    if (batchFlow.getEndDate().equals(0)) {
                        batchFlow.setDataState(null);
                    }
                    if (batchFlow.getBatchFlowId() != null) {
                        if (batchFlow.getBatchFlowId().equals(0)) {
                            batchFlow.setBatchFlowId(null);
                            //根据ID得到编号
                            batchFlow.setBatchCode(batchMapper.selectById(batchFlow.getBatchId()));
                            insertrow = insertrow + batchFlowMapper.insertBatchFlow(batchFlow);
                            //带出  工位和不良
                            Integer newFlow = batchFlow.getBatchFlowId();
                            Integer proId = batchFlow.getProId();

                            //查询工序下工位
                            Pro pro = new Pro();
                            pro.setProId(proId);

                            List<ProStation> proStations = proStationMapper.queryByProId(proId);
                            //带出  工位
                            for (int i = 0; i < proStations.size(); i++) {
                                BatchStation batchStation = new BatchStation();
                                batchStation.setBatchFlowId(newFlow);
                                batchStation.setStationId(proStations.get(i).getStationId());
                                batchStation.setDataState(1);
                                batchStationMapper.insertBatchStation(batchStation);
                            }

                            //带出  工位和不良  完成

                        } else {
                            //根据ID得到编号
                            batchFlow.setBatchCode(batchMapper.selectById(batchFlow.getBatchId()));
                            updaterow = updaterow + batchFlowMapper.updateBatchFlow(batchFlow);
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 保存维修流程
     */
    @Override
    public JSONObject saveBatchRepair(Batch batch) {
        try {
            //判空
            if (batch == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (batch.getBatchId() == null) {
                throw new ParamsErrorException(HintMessage.ORDERID_NULL);
            }

            //获取版本
            Integer batchId = batch.getBatchId();
            //获取list集合
            List<BatchRepair> batchRepairList = new ArrayList<>();
            batchRepairList = batch.getBatchRepairList();
            for (BatchRepair batchRepair : batchRepairList) {
                batchRepair.setBatchId(batchId);
            }


            //获取数据库数据
            BatchRepair batchRepair1 = new BatchRepair();
            batchRepair1.setBatchId(batchId);

            List<BatchRepair> oldbatchRepairList = batchRepairMapper.queryBatchRepair(batchRepair1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldbatchRepairList != null) {
                for (BatchRepair batchRepair : oldbatchRepairList
                ) {
                    oldIds.add(batchRepair.getBatchRepairId());
                }
            }
            if (batchRepairList != null) {
                for (BatchRepair batchRepair : batchRepairList
                ) {
                    newIds.add(batchRepair.getBatchRepairId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = batchRepairMapper.deleteBatchRepair(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (batchRepairList != null) {
                for (BatchRepair batchRepair : batchRepairList
                ) {
                    if (batchRepair.getDataState() == null) {
                        batchRepair.setDataState(1);
                    }


                    if (batchRepair.getBatchRepairId() != null) {
                        if (batchRepair.getBatchRepairId().equals(0)) {
                            batchRepair.setBatchRepairId(null);
                            insertrow = insertrow + batchRepairMapper.insertBatchRepair(batchRepair);


                        } else {
                            updaterow = updaterow + batchRepairMapper.updateBatchRepair(batchRepair);
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    @Override
    public JSONObject queryBatchAll(Batch batch) {
        List<Batch> batchList = null;
        try {
            Integer pagesize = batch.getPagesize();
            Integer pageindex = batch.getPageindex();
            if (pagesize != null && pageindex != null) {
                batch.setIncept(pagesize * (pageindex - 1));
            }
            //查询全部
            batchList = batchMapper.queryBatchAll(batch);
            if (batchList.isEmpty()) {
                return JSONObject.oK("没有查询到数据", batchList, 0);
            }
            //查询分页总记录数
            int count = batchMapper.countBatchAll(batch); //返回查询到的总记录数
            return JSONObject.oK("查询成功", batchList, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

}
